//
//  ScrollViewViewController.m
//  Masory使用
//
//  Created by 周成龙 on 16/10/28.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "ScrollViewViewController.h"

#import "Masonry.h"

@interface ScrollViewViewController ()
@property (strong, nonatomic) UIScrollView* scrollView;
@end

@implementation ScrollViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initView];
}

- (void)initView {
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(64, 0, 0, 0));
    }];
    
    UIView *superView = bgView;
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor grayColor];
    [superView addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
    
    [self addChildViews];
}

- (void)addChildViews {
    UIView *contentView = [[UIView alloc] init];
    [self.scrollView addSubview:contentView];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
   
    CGFloat height = 25;
    UIView *lastView = nil;
    for (int i=0; i < 10; i ++) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [self randomColor];
        [contentView addSubview:view];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        [view addGestureRecognizer:singleTap];
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lastView ? lastView.mas_bottom : @0);
            make.left.equalTo(contentView);
            make.width.equalTo(contentView);
            make.height.equalTo(@(height));
        }];
        
        height += 10;
        lastView = view;
    }
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView.mas_bottom);
    }];
}

- (UIColor *)randomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (void)singleTap:(UITapGestureRecognizer*)sender {
    [sender.view setAlpha:sender.view.alpha / 1.20];
    [self.scrollView scrollRectToVisible:sender.view.frame animated:YES];
}

@end
